<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img :src="avatar" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input
          type="file"
          name=""
          id=""
          ref="inputFile"
          style="display: none"
          @change="upload"
        />
        <el-button type="primary" icon="el-icon-plus" @click="changeImg"
          >选择图片</el-button
        >
        <el-button
          type="success"
          icon="el-icon-upload"
          :disabled="avatar === ''"
          @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
import { changeAvatar } from '@/api'
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    changeImg () {
      this.$refs.inputFile.click()
    },
    upload (e) {
      const file = e.target.files[0]
      const fr = new FileReader() // 将图片转化为base64格式
      fr.readAsDataURL(file)
      fr.onload = () => {
        this.avatar = fr.result
      }
    },
    async uploadAvatar () {
      const res = await changeAvatar(this.avatar)
      if (res.data.code !== 0) return
      this.$message.success('更新头像成功')
      this.$store.dispatch('userInfoHandle')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}
</style>
